/*
 *  $Id: DirectConnect.cs 1239 2011-03-23 12:51:24Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008-2009 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

namespace Ragima {
    public class DirectConnectGameMode: GameMode {
        private Connection _connection;
        private bool _master;
        private PlayerInfo _remotePlayer;

        public DirectConnectGameMode(): base() {
            _connection = new Connection();
            _connection.OnConnect += DoConnect;
            _connection.OnDisconnect += DoDisconnect;
            _connection.OnReceiveEvent += AddRemoteEvent;
            _remotePlayer = null;
        }

        public override PlayerInfo Player1 {
            get { return Application.Config.Player1; }
        }
        public override PlayerInfo Player2 {
            get { return _remotePlayer; }
        }

        public override bool Master {
            get { return _master; }
        }

        public override Player GetMainPlayer(bool side, Player player1, Player player2) {
            return player1;
        }

        public override void AddEvent(Events.AbstractEvent ev) {
            base.AddEvent(ev);
            if (ev.NeedSend)
                SendEvent(ev);
        }

        private void AddRemoteEvent(Events.AbstractEvent ev) {
            base.AddEvent(ev);
        }

        public void SendEvent(Events.AbstractEvent ev) {
            // FIXME : temporary event log
            ev.WriteToConsole("Send");
            _connection.SendEvent(ev);
        }

        public override void ProcessEvents(OldScene scene) {
            ReceiveEvents();
            base.ProcessEvents(scene);
        }

        public void ReceiveEvents() {
            _connection.ReceiveEvents();
        }

        public void ConnectToGame(string addr) {
            _master = false;
            _remotePlayer = null;
            _connection.Connect(addr);
        }

        public bool CreateGame() {
            _master = true;
            _remotePlayer = null;
            return _connection.WaitConnect();
        }

        public void CancelCreateGame() {
            _connection.CancelWaitConnect();
        }

        public void DisconnectGame() {
            _connection.Disconnect();
        }

        public void SetRemotePlayer(PlayerInfo info) {
            _remotePlayer = info;
        }

        private void DoConnect() {
            AddEvent(new Events.Connect(_connection.Connected, _connection.EndPoint));
        }

        private void DoDisconnect() {
            _remotePlayer = null;
            AddEvent(new Events.Disconnect());
        }
    }
}
